/* eslint global-require: off, no-console: off */

import crypto from 'crypto';
import path from 'path';
import MenuBuilder from './menu';
import { app, BrowserWindow, ipcMain, shell } from 'electron';
import log, { FileTransport, PathVariables } from 'electron-log';
import { registerElectronProtocolWhenAppRead } from '@utils/electronProtocol';
import windowManager from '@utils/windowManager';

const createWindow = async () => {
  registerElectronProtocolWhenAppRead();

  const mainWindow = windowManager.createWindow({
    name: 'main',
    isMain: true,
  });

  mainWindow.once('ready-to-show', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
      mainWindow.focus();
    }

  });

  mainWindow.on('close', (event) => {
    mainWindow?.webContents.send('request-window-close');
    event.preventDefault();
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();

  // Open urls in the user's browser
  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url);
    return { action: 'deny' };
  });

};

app.on('window-all-closed', () => {
  // Note: We don't have to follow Darwin Convention, this is fucking stupid and unintuitive
  app.quit();
});

app.on('activate', () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

app.on('will-quit', (event) => {
  const wins = BrowserWindow.getAllWindows();
  if (wins.length) {
    wins.forEach((win) => win.webContents.send('request-window-close'));
    event.preventDefault();
  }
});

ipcMain.on('external-window', (_, arg) => shell.openExternal(arg));

app.whenReady().then(createWindow).catch(log.error);
